//
//  MeetingRequestTableViewController.m
//  KurtulusLaw
//
//  Created by Mahmood1 on 12/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MeetingRequestTableViewController.h"
#import "Constant.h"
#import "MeetingRequestCell.h"
#import <QuartzCore/QuartzCore.h>
#import "ActionSheetStringPicker.h"
#import "ActionSheetDistancePicker.h"
#import "CKCalendarView.h"
#import "UIPlaceHolderTextView.h"
#import "KMeetingRequestCommandDTO.h"
#import "CCommon.h"
#import "KMeetingRequestDAO.h"
#import "UserService.h"
#import "UserDTO.h"
#import "MBProgressHUD.h"
#import "LoginViewController.h"


@interface MeetingRequestTableViewController ()<CKCalendarDelegate, UITextViewDelegate, ActionSheetDistancePickerDelegate, UITextFieldDelegate> {
    NSMutableArray *_sectionTitleArray;
    NSMutableArray *_cellTitleArray1;
    NSMutableArray *_ArrayValuesofcell;
    NSMutableArray *_SelectionValueArray;
    NSMutableArray  *_CellTitleImageArray1;
    CKCalendarView *calendar;
    NSString       *_subjectText;
    NSString       *_metorRequestText;
    
    UIPlaceHolderTextView *_subjectTextView;
    UIPlaceHolderTextView *_mentorTextView;
    UITableView *_tableView;
    
    UITextField *_relatedLawyerTextField;
	MBProgressHUD *_progressHUD;
	UILabel *_titleView;
	UIButton *_metorButton;
	BOOL _isMetorChecked;
	UITapGestureRecognizer *oneTaps;
}

@end

@implementation MeetingRequestTableViewController
@synthesize tableView = _tableView;

#define kBackgroundColor [UIColor colorWithRed:101/255.0f green:101/255.0f blue:101/255.0f alpha:1]
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)hideCalendar:(id)sender {
    [calendar setHidden:YES];
    CGRect frame = self.tableView.frame;
    frame.size.height = self.view.frame.size.height;
    self.tableView.frame = frame;
}

- (void)showCalendar:(id)sender {
    [calendar setHidden:NO];
    
    [self.view addSubview:calendar];
    
    // Create gesture recognizer
    oneTaps = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView:)];
    
    // Set required taps and number of touches
    [oneTaps setNumberOfTapsRequired:1];
    [oneTaps setNumberOfTouchesRequired:1];
    
    // Add the gesture to the view
    CGRect frame = self.tableView.frame;
    frame.size.height = calendar.frame.origin.y;
    self.tableView.frame = frame;
    [[self tableView] addGestureRecognizer:oneTaps];

}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    // Do any additional setup after loading the view from its nib.
    _titleView = [[UILabel alloc] initWithFrame:CGRectMake(45,6,280,30)];
    _titleView.text = NSLocalizedString(@"Meeting Request", nil);
    _titleView.font = [UIFont boldSystemFontOfSize:18.0f];
    _titleView.textColor = [UIColor whiteColor];
    _titleView.backgroundColor = [UIColor clearColor];
    
    [self.navigationController.navigationBar addSubview: _titleView];
    
    if ([self.navigationController.parentViewController respondsToSelector:@selector(revealGesture:)] && [self.navigationController.parentViewController respondsToSelector:@selector(revealToggle:)])
	{
		UIPanGestureRecognizer *navigationBarPanGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self.navigationController.parentViewController action:@selector(revealGesture:)];
		[self.navigationController.navigationBar addGestureRecognizer:navigationBarPanGestureRecognizer];

        UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 30, 46)];
        [backButton setImage:[UIImage imageNamed:@"sidebar-30x46.png"] forState:UIControlStateNormal];
        [backButton addTarget:self.navigationController.parentViewController action:@selector(revealToggle:) forControlEvents:UIControlEventTouchUpInside];
        //self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
        [self.navigationController.navigationBar addSubview:backButton];

	}
    
	_progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
	_progressHUD.taskInProgress = YES;
	_progressHUD.progress = 0.5;
    _progressHUD.dimBackground = YES;
	
	_progressHUD.labelText = NSLocalizedString(@"Loading", nil);
	[_progressHUD setUserInteractionEnabled:YES];
	[self.view addSubview:_progressHUD];
	
    self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(8, 0, 304, 460) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
	NSString *strSection1 = NSLocalizedString(@"Organise your Meeting", nil);
	NSString *strSection2 = NSLocalizedString(@"Subject & Notes", nil);
	NSString *strSection3 = NSLocalizedString(@"Mentor Request (Prof, Academician...)", nil);
	
    _sectionTitleArray = [[NSMutableArray alloc] initWithObjects: strSection1,strSection2,strSection3, nil];
    _cellTitleArray1 = [[NSMutableArray alloc] initWithObjects:NSLocalizedString(@"Date", nil), NSLocalizedString(@"Time", nil), NSLocalizedString(@"Duration", nil), NSLocalizedString(@"Place", nil), NSLocalizedString(@"Language", nil), NSLocalizedString(@"Translater Request", nil), NSLocalizedString(@"Type", nil), NSLocalizedString(@"Record the meeting", nil), NSLocalizedString(@"Related Lawyer", nil), nil];
    
    _ArrayValuesofcell = [[NSMutableArray alloc] initWithObjects:[[NSMutableArray alloc] init], [[NSMutableArray alloc] init], nil];
    [_ArrayValuesofcell addObject:[NSMutableArray arrayWithObjects:@"30",  @"45", @"60", @"75",@"90", nil]];
    [_ArrayValuesofcell addObject:[NSMutableArray arrayWithObjects:NSLocalizedString(@"Internet", nil), NSLocalizedString(@"Client office", nil), NSLocalizedString(@"Our office", nil), NSLocalizedString(@"If other please type in notes", nil), nil]];
       [_ArrayValuesofcell addObject:[NSMutableArray arrayWithObjects:@"Turkish", @"English", @"German", @"Russian", @"Arabic", @"Persian", @"French", @"Italian", @"Spanish", @"Chinese", @"Korean", @"Japanese", NSLocalizedString(@"If other please type in notes", nil), nil]];
    [_ArrayValuesofcell addObject:[NSMutableArray arrayWithObjects:NSLocalizedString(@"No", nil), NSLocalizedString(@"Yes(Type in notes)", nil), nil]];
    [_ArrayValuesofcell addObject:[NSMutableArray arrayWithObjects:NSLocalizedString(@"Phone", nil),@"Skype", NSLocalizedString(@"Face to Face", nil), nil]];
    [_ArrayValuesofcell addObject:[NSMutableArray arrayWithObjects:NSLocalizedString(@"No", nil), NSLocalizedString(@"Yes(Type in notes)", nil), nil]];
    [_ArrayValuesofcell addObject:[[NSMutableArray alloc] init]];
    
    
    NSDateFormatter *dateFormatter = [NSDateFormatter alloc];
    dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"M/d/y"];
    
    _SelectionValueArray = [NSMutableArray arrayWithObjects:[dateFormatter stringFromDate:[[NSDate alloc] init]], @"21:15", @"45", NSLocalizedString(@"Internet", nil), @"Turkish", @"0", NSLocalizedString(@"Phone", nil), @"0", @"", nil];
    
    _CellTitleImageArray1 = [[NSMutableArray alloc] initWithObjects:kImageMeetingDateIcon28x28,kImageMeetingTimeIcon28x28, kImageMeetingDurationIcon30x28, kImageMeetingPlaceIcon30x28, kImageMeetingLanguageIcon28x28, kImageMeetingTranslateIcon28x28, kImageMeetingTypeIcon28x28, kImageMeetingCamraIcon32x28, kImageMeetingLawyerIcon22x28, nil];
    
    
    [self.tableView setSeparatorColor:kBackgroundColor];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 304, 49)];
    [btn setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:kImageMeetingSendRequestBtnBg]]];
    [btn setTitle: NSLocalizedString(@"Send My Request", nil) forState:UIControlStateNormal];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 304, 150)];
    [footerView setBackgroundColor:[UIColor clearColor]];
    [footerView addSubview:btn];
	[btn addTarget:self action:@selector(touchDownSendRequest:) forControlEvents:UIControlEventTouchUpInside];
	
    self.tableView.tableFooterView = footerView;
    
    calendar = [[CKCalendarView alloc] initWithStartDay:startMonday];
    calendar.delegate = self;
    calendar.selectedDate = [[NSDate alloc] init];
    
    calendar.frame = CGRectMake(0, 140, 320, 320);
    [self hideCalendar:nil];
    [self.view addSubview:calendar];
        
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav-bg-gray"] forBarMetrics:UIBarMetricsDefault];
    
    _subjectText = @"";
    _metorRequestText = @"";
    
    //[self.tableView setBackgroundColor:[UIColor clearColor]];
	[self.tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:kImageBackgroundForRightSideView]]];
    
    [self.tableView setBackgroundView:nil];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:kImageBackgroundForRightSideView]]];
}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return section == 2 ? 50 : 10;
//}

- (void)tapView:(id)sender {
    [self hideCalendar:nil];
    
    [self.tableView removeGestureRecognizer:sender];
}

- (void)touchDownSendRequest:(id)sender {
	KMeetingRequestCommandDTO *meetingReuqest = [[KMeetingRequestCommandDTO alloc] initWithSessionID:[CCommon shareSessionID]];
	
	NSString *dateTimeValue = [NSString stringWithFormat:@"%@ %@",[_SelectionValueArray objectAtIndex:0], [_SelectionValueArray objectAtIndex:1]];
	meetingReuqest.meeting_date = [dateTimeValue copy];
	meetingReuqest.meeting_duration = [[_SelectionValueArray objectAtIndex:2] integerValue];
	meetingReuqest.meeting_place = [[_SelectionValueArray objectAtIndex:3] copy];
	meetingReuqest.meeting_language = [[_SelectionValueArray objectAtIndex:4] copy];
	meetingReuqest.meeting_type = [[_SelectionValueArray objectAtIndex:6] copy];
	meetingReuqest.meeting_record = [[_SelectionValueArray objectAtIndex:7] boolValue];
	meetingReuqest.meeting_notes = [_subjectTextView.text copy];
	meetingReuqest.mentor_required = [_mentorTextView.text copy];
	meetingReuqest.mentor_request= _isMetorChecked;
	
	[_progressHUD show:YES];
	
	BOOL b = [KMeetingRequestDAO meetingRequest:meetingReuqest
		block:^(NSInteger isSuccess, NSError *error) {
		 switch (isSuccess) {
			 case OK:
				 [[[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Message", nil) message: NSLocalizedString(@"You sent a meeting request", nil) delegate:nil cancelButtonTitle: NSLocalizedString(@"OK",nil) otherButtonTitles:nil, nil] show];
				 break;
			 case NOT_VALID:
				 [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message:NSLocalizedString(@"You don't send a meeting request", nil) delegate:nil cancelButtonTitle: NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil] show];
				 break;
			 case NOT_AUTHENTICATE:
				 [UserService checkLoginWithUserName:[CCommon shareUsername] pass:[CCommon sharePassword] :^(id dictionary, NSError *error) {
					 if (error) {
						 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil)  message: [error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil)  otherButtonTitles:nil, nil];
						 [alert show];
						 [_progressHUD hide:YES];
					 }
					 else
					 {
						 @try {
						
							 if ([[dictionary objectForKey:@"status"] isEqualToString:@"OK"]) {
								 [CCommon setSesionID: [dictionary objectForKey: kKEY_SESSION_ID]];
								 [_progressHUD hide:YES];
								 [self touchDownSendRequest:sender];
							 }
							 else
							 {
								 LoginViewController *login = [[LoginViewController alloc] init];
								 login.navigationItem.hidesBackButton = YES;
								 login.isFristLogin = NO;
								 [_titleView removeFromSuperview];
								 
								 [self.navigationController pushViewController:login animated:YES];
							 }
						 }
						 @catch (NSException *exception) {
							 [_progressHUD hide:YES];
						 }
						 @finally {
							 //
						 }
					 }
				 }];
				 break;
				 
		 } 
		}];
	
	if (!b) {
		[_progressHUD hide:YES];
	}
}

- (void)tapTextView:(id)sender {
    
    [_mentorTextView resignFirstResponder];
    [_subjectTextView resignFirstResponder];
    [_relatedLawyerTextField resignFirstResponder];
    [self.view removeGestureRecognizer:sender];
}

-(void)tapDetected :(id)sender
{
    
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    switch (section) {
        case 0:
            return 9;
        case 1:
            return 1;
            break;
        case 2:
            return 1;
            break;
        default:
            break;
    }
    return 0;
}
- (void)SetStateMetorButton:(BOOL) isChecked {
	_isMetorChecked = isChecked;
	if (isChecked) {		
		[_metorButton setImage:[UIImage imageNamed:kImageCheckBoxOn] forState:UIControlStateNormal];
	} else {
		[_metorButton setImage:[UIImage imageNamed:kImageCheckBoxOff] forState:UIControlStateNormal];
	}
}

- (void)touchDownMetorButton {
	[self SetStateMetorButton:!_isMetorChecked];
}
- (UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
     UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 32)];
    [header setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:kImageBackgroundForRightSideView]]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 320, 32)];
    label.backgroundColor = [UIColor clearColor];
    [label setText:[_sectionTitleArray objectAtIndex:section]];
    [label setTextColor:[UIColor whiteColor]];
    [label sizeToFit];
    [label setFont:[UIFont boldSystemFontOfSize:15]];
    [header addSubview:label];
    
    if (section == 2) {
		
		if (!_metorButton) {
			_metorButton = [[UIButton alloc] initWithFrame:CGRectMake(2, 0, 24, 24)];
			
			[_metorButton addTarget:self action:@selector(touchDownMetorButton) forControlEvents:UIControlEventTouchUpInside];
			[self SetStateMetorButton:_isMetorChecked];
		}
		
       
        [header addSubview:_metorButton];
        
        [label setFrame:CGRectMake(30, 0, header.frame.size.width - 30, 32)];
         [_metorButton setCenter:CGPointMake(_metorButton.center.x, label.center.y)];
    }
    
    return header;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 32;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
      
    }
    
    switch (indexPath.section) {
        case 0:
        {
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:kMeetingRequestsCell owner:nil options:nil];
            for (UIView *view in views) {
                if([view isKindOfClass:[MeetingRequestCell class]])
                {
                    cell = (MeetingRequestCell*)view;                  
                    
                }
            }
        
            MeetingRequestCell *requestCell = (MeetingRequestCell*) cell;
            [requestCell.mainView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:kImageMeetingCell]]];
            [requestCell.titleLabel setText:[_cellTitleArray1 objectAtIndex:indexPath.row]]; 
            [requestCell.titleLabel setTextColor:[UIColor grayColor]];
            [requestCell.valueLabel setTextColor:[UIColor grayColor]];
            [requestCell.texFiled setTextColor:[UIColor grayColor]];
            //TODO: Set image
            [requestCell.titleImageView setImage:[UIImage imageNamed:[_CellTitleImageArray1 objectAtIndex:indexPath.row]]];
            [requestCell.titleImageView setCenter:CGPointMake(119, 17)];
           
            if (indexPath.row == 8) {
                [requestCell.valueLabel setHidden:YES];
                
                if (_relatedLawyerTextField == nil) {
                    _relatedLawyerTextField = [[UITextField alloc] initWithFrame:requestCell.texFiled.frame];
                    _relatedLawyerTextField.delegate = self;
                    [_relatedLawyerTextField setPlaceholder: NSLocalizedString(@"Type", nil)];
                    
                    [_relatedLawyerTextField setBackground:[UIImage imageNamed:@"meeting-textfield-bg-139x34.png"]];
                    [_relatedLawyerTextField setFont:[UIFont systemFontOfSize:14]];
                    [_relatedLawyerTextField setTextColor:[UIColor darkGrayColor]];
                }
                
                [requestCell.contentView addSubview:_relatedLawyerTextField];
                requestCell.texFiled = _relatedLawyerTextField;

            } else if (indexPath.row == 2) {
				[requestCell.valueLabel setText:[NSString stringWithFormat:@"%@ %@", [_SelectionValueArray objectAtIndex:indexPath.row],NSLocalizedString(@"Minutes", nil)]];
				} else if (indexPath.row == 5 || indexPath.row == 7) {
					NSString *selectionValue = [_SelectionValueArray objectAtIndex:indexPath.row];
					
					NSString *showingValue = @"";
					if ([selectionValue isEqualToString:@"0"]) {
						showingValue = @"No";
					} else {
						showingValue = @"Yes";
					}
					
					[requestCell.valueLabel setText:showingValue];
					
				} else {
					[requestCell.valueLabel setText:[_SelectionValueArray objectAtIndex:indexPath.row]];
				}
                 
            break;
        }
        case 1: {
            
            if (_subjectTextView == nil) {
                _subjectTextView = [[UIPlaceHolderTextView alloc] initWithFrame:CGRectMake(0, 0, 304, 84)];
                
                [_subjectTextView setBackgroundColor:[UIColor whiteColor]];
                
                [_subjectTextView setPlaceholder: NSLocalizedString(@"Please give us more details", nil)];
                _subjectTextView.delegate = self;
               CGRect frame =  _subjectTextView.placeHolderLabel.frame;
                frame.origin.y = 0;
                _subjectTextView.placeHolderLabel.frame = frame;
            }
            
            [cell.contentView addSubview:_subjectTextView];
            [cell setBackgroundColor:[UIColor whiteColor]];
            break;
        }
        case 2:
        {
            if (_mentorTextView == nil) {
                _mentorTextView = [[UIPlaceHolderTextView alloc] initWithFrame:CGRectMake(0, 0, 304, 50 )];
                
                [_mentorTextView setBackgroundColor:[UIColor whiteColor]];
                [_mentorTextView setPlaceholder:NSLocalizedString(@"Please give us more details if you have a mentor request", nil)];
                _mentorTextView.delegate = self;
                
                CGRect frame =  _mentorTextView.placeHolderLabel.frame;
                frame.origin.y = 0;
                _mentorTextView.placeHolderLabel.frame = frame;
            }
           
            [cell setBackgroundColor:[UIColor whiteColor]];

            [cell.contentView addSubview:_mentorTextView];
//            [_metorRequestText setText:_mentorTextView];    
            break;
        }
        default:
            break;
    }
    
    // Configure the cell...
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
         return 34;
    } else if (indexPath.section == 1) {
         return 84;
    } else if (indexPath.section == 2) {
         return 50;
    }
    
    return 0;
   
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate
- (void)measurementWasSelectedWithBigUnit:(NSNumber *)bigUnit smallUnit:(NSNumber *)smallUnit element:(id)element {
  [bigUnit intValue];
   [smallUnit intValue];
    [element setText:[NSString stringWithFormat:@"%i m and %i cm", [bigUnit intValue], [smallUnit intValue]]];
}

- (void)actionSheetPicker:(ActionSheetDistancePicker *)picker bigUnits:(NSInteger)bigUnits smallUnits:(NSInteger)smallUnits {
    NSString *time  = [NSString stringWithFormat:@"%2d : %2d", bigUnits, smallUnits];
    
    [_SelectionValueArray replaceObjectAtIndex:1 withObject:time ];
    
    [self.tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
    
    ActionSheetStringPicker *picker;
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
            {
                [self showCalendar:nil];
                break;
            }
            case 1:
            {
				picker = [ActionSheetDistancePicker showPickerWithTitle:NSLocalizedString(@"Time", nil) selectedBigUnit:21 selectedSmallUnit:15 target:self origin:self.view] ;
                break;
            }
            case 2:
			{
				NSMutableArray *showingValues = [[NSMutableArray alloc] init];
				
				for (NSString *value in [_ArrayValuesofcell  objectAtIndex:indexPath.row]) {
					[showingValues addObject:[NSString stringWithFormat:@"%@ %@", value,NSLocalizedString(@"Minutes", nil)]];
				}
				
				picker = [ActionSheetStringPicker showPickerWithTitle: NSLocalizedString(@"Picker", nil) rows:[_ArrayValuesofcell objectAtIndex:indexPath.row] initialSelection:0 doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id sender) {
                    NSString *selectedItem = [[_ArrayValuesofcell objectAtIndex:indexPath.row] objectAtIndex:selectedIndex ];
                    
					if (indexPath.row == 5 || indexPath.row == 7) {
						
					} else {
						[_SelectionValueArray replaceObjectAtIndex:indexPath.row withObject:selectedItem]; 
					}
					
                    [self.tableView reloadData];
                } cancelBlock:^(ActionSheetStringPicker *picker) {
                    
                } origin:self.view];
				
			}
				break;
            
			case 7:
            case 5:
			case 3:
            case 4:
            case 6:
            
            
                picker = [ActionSheetStringPicker showPickerWithTitle:NSLocalizedString(@"Picker", nil) rows:[_ArrayValuesofcell objectAtIndex:indexPath.row] initialSelection:0 doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id sender) {
                    NSString *selectedItem = [[_ArrayValuesofcell objectAtIndex:indexPath.row] objectAtIndex:selectedIndex ];
					
					[_SelectionValueArray replaceObjectAtIndex:indexPath.row withObject:selectedItem]; 
                   
                    [self.tableView reloadData];
                } cancelBlock:^(ActionSheetStringPicker *picker) {
                    
                } origin:self.view];
                
                break;
        }
    }
}

#pragma mark - CKCalendarDelegate

- (void)calendar:(CKCalendarView *)calendar didSelectDate:(NSDate *)date {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"M/d/y"];
    [_SelectionValueArray replaceObjectAtIndex:0 withObject:[dateFormatter stringFromDate:date]];
    [self.tableView reloadData];
    [self hideCalendar:nil];
    
}


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    // Create gesture recognizer
    oneTaps = 
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTextView:)];
    
    // Set required taps and number of touches
    [oneTaps setNumberOfTapsRequired:1];
    [oneTaps setNumberOfTouchesRequired:1];
    
    // Add the gesture to the view
    [[self view] addGestureRecognizer:oneTaps];
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self tapTextView:oneTaps];
   	
    return YES;
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
	
	oneTaps = 
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTextView:)];
    
    // Set required taps and number of touches
    [oneTaps setNumberOfTapsRequired:1];
    [oneTaps setNumberOfTouchesRequired:1];
    
    // Add the gesture to the view
    [[self view] addGestureRecognizer:oneTaps];

	return YES;
}
@end
